package com.roger.springcloudGreenwich.controller;

import com.roger.springcloudGreenwich.pojo.Users;
import com.roger.springcloudGreenwich.service.LockService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * Created by yulei on 2020/4/4.
 */
@RestController
@Slf4j
public class TestController {

    @Value("${spring.application.name}")
    private String name;

    @GetMapping("/login/{userNo}")
    public String login(@PathVariable String userNo, HttpSession session){
        System.out.println("login");
        session.setAttribute("user" , userNo);
        return new Date() + "success:" + name;
    }

    @GetMapping("/error/{id}")
    public String error(@PathVariable int id){
        if(id == 0){
            throw new  RuntimeException("抛出异常");
        }else{
            return "success";
        }
    }

    @GetMapping(value = "getSession")
    public Object getSession(HttpServletRequest request){
        HttpSession session = request.getSession(true);
        log.info("session id==={}", session.getId());
        return session.getAttribute("user");
    }

    @PostMapping(value = "/findUser",produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Users findUser(@RequestBody Users users){
        log.info("users==={}", users);
        return users;
    }



    @Resource
    private LockService lockService;

    @RequestMapping("/buyTicket/{id}")
    public void buyTicket(@PathVariable int id) {
        ExecutorService executor = Executors.newCachedThreadPool();
        for (int i = 0; i < 5000; i++ ) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    lockService.buyTicket(id);
                }
            });
        }
    }

    @GetMapping("/test/{id}")
    public TUser user(@PathVariable int id) {
        TUser user = new TUser();
        user.setId(1);
        user.setUsername("roger");
        return user;
    }

    public class TUser{
        private Integer id;
        private String username;

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }
    }

}
